﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace MensUnoShop.Areas.Admin.Models
{
    public class UploadImage
    {

        /// <summary>
        /// 儲存上傳圖檔
        /// </summary>
        /// <param name="ADimage"></param>
        /// <param name="NewFileNameTopHeader">新檔名開頭</param>
        /// <param name="ifwantTransImage">是否要縮圖</param>
        /// <param name="TargetWidth">縮圖寬度</param>
        /// <returns></returns>
        private SaveUploadMessage _mSaveUploadImage(HttpPostedFileBase image, string AppSettingsDir, string NewFileNameTopHeader, bool ifwantTransImage, int TargetWidth)
        {
            SaveUploadMessage ss = new SaveUploadMessage();
            string OutPutMainDirectoryStr = AppSettingsDir;
            //string OutPutMainDirectoryStr = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadBestKiller"];
            //主目錄字串
            //string OutPutDirName = DateTime.Now.ToString("yyyyMMdd");
            //上傳目錄字串
            string OutPutDirStr = OutPutMainDirectoryStr;// + OutPutDirName;
            //上傳目錄實體路徑字串

            DirectoryInfo OutPutDir = new DirectoryInfo(HttpContext.Current.Server.MapPath(OutPutDirStr));

            /*紀錄*/
            LogDataRecord.LDR log9 = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
            log9.RecordException("上傳目錄實體路徑:" + OutPutDir.FullName, "SaveUploadImage");

            //上傳目錄實體路徑
            if (!OutPutDir.Exists)
            {
                try
                {
                    //建立目錄
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(OutPutDirStr));
                }
                catch (Exception ex)
                {
                    LogDataRecord.LDR log1 = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
                    log1.RecordException(ex.GetBaseException().ToString(), "SaveUploadImage");
                }
            }



            //建立完目錄，處理上傳檔案

            string OutPutNewFileName = "";
            //上傳後新檔名
            string OutPutNewFileStr = "";
            //新檔案實體路徑字串
            string iExtension = "";
            try
            {
                LogDataRecord.LDR log13 = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
                log13.RecordException("log13:" + image.ToString(), "SaveUploadImage");

                iExtension = Path.GetExtension(image.FileName).ToLower();
            }
            catch (Exception ex)
            {
                LogDataRecord.LDR log12 = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
                log12.RecordException("log12:" + ex.GetBaseException().ToString(), "SaveUploadImage");
            }

            /*紀錄*/
            LogDataRecord.LDR log2 = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
            log2.RecordException("取得圖檔副檔名:" + iExtension, "SaveUploadImage");

            //取得圖檔副檔名
            if ((iExtension == ".jpg") || (iExtension == ".bmp") || (iExtension == ".png") || (iExtension == ".gif"))
            {
                //驗證圖片格式
                OutPutNewFileName = NewFileNameTopHeader + "_" + DateTime.Now.ToString("hhmmss") + iExtension;
                //上傳後新檔名
                OutPutNewFileStr = OutPutDirStr + "\\" + OutPutNewFileName;
                //新檔案實體路徑字串
                //OutPutFile = Path.Combine(OutPutDir.ToString(), OutPutFileNewName);

                /*紀錄*/
                LogDataRecord.LDR log3 = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
                log3.RecordException("上船後新黨名:" + OutPutNewFileName + "新檔案實體路徑字串:" + OutPutNewFileStr, "SaveUploadImage");


                try
                {
                    image.SaveAs(HttpContext.Current.Server.MapPath(OutPutNewFileStr));
                    //ss.NewFileName = OutPutDirName + "/" + OutPutNewFileName;
                    ss.NewFileName = OutPutNewFileName;
                }
                catch (Exception ex)
                {
                    /*紀錄*/
                    LogDataRecord.LDR log4 = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
                    log4.RecordException(ex.GetBaseException().ToString(), "SaveUploadImage");
                }

                FileInfo uploadfileCheck = new FileInfo(HttpContext.Current.Server.MapPath(OutPutNewFileStr));
                if (uploadfileCheck.Exists)
                {
                    //檔案存在
                    ss.saveStatus = true;
                    if (ifwantTransImage)
                    {

                        //需要縮圖
                        string OutPutNewFileTransName = NewFileNameTopHeader + "_" + DateTime.Now.ToString("hhmmss") + "_trans" + iExtension;
                        //新縮圖檔名
                        string OutPutNewFileTransStr = OutPutDirStr + "\\" + OutPutNewFileTransName;
                        //新縮圖實體路徑字串
                        TransformImage(HttpContext.Current.Server.MapPath(OutPutNewFileStr), HttpContext.Current.Server.MapPath(OutPutNewFileTransStr), TargetWidth, true, 80);
                        //縮圖
                        //ss.NewFileName = OutPutDirName + "/" + OutPutNewFileTransName;
                        ss.NewFileName = OutPutNewFileTransName;
                        //取得新的圖片路徑
                    }
                }
                else
                {
                    ss.saveStatus = false;
                    ss.SaveErrorMessage = "圖片上傳失敗，無法確定檔案存在";
                }
            }
            else
            {
                ss.saveStatus = false;
                ss.SaveErrorMessage = "圖片檔案格式不符合規定";
            }
            return ss;
        }

        /// <summary>
        /// 縮圖
        /// </summary>
        /// <param name="SourceFile"></param>
        /// <param name="TargetFile"></param>
        /// <param name="iWidth"></param>
        /// <param name="EnableHQJPG"></param>
        /// <param name="EncodePercentage"></param>
        private void TransformImage(string SourceFile, string TargetFile, int iWidth, bool EnableHQJPG, long EncodePercentage)
        {
            Bitmap bmpSource = new Bitmap(SourceFile);
            FileStream OutStream = new FileStream(TargetFile, FileMode.Create);
            double ratio = (double)iWidth / (double)bmpSource.Width;

            Bitmap bmpTarget = new Bitmap((int)(bmpSource.Width * ratio), (int)(bmpSource.Height * ratio));
            Graphics g = Graphics.FromImage((System.Drawing.Image)bmpTarget);
            try
            {
                #region
                switch (Path.GetExtension(SourceFile).ToLower())
                {
                    case ".bmp":
                    case ".jpg":
                    case ".jpeg":
                        if (EnableHQJPG)
                        {
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
                            System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
                            eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, EncodePercentage);
                            g.DrawImage((System.Drawing.Image)bmpSource, 0, 0, (int)(bmpSource.Width * ratio), (int)(bmpSource.Height * ratio));
                            g.Dispose();
                            bmpTarget.Save(OutStream, codec, eParams);
                        }
                        else
                        {
                            g.DrawImage((System.Drawing.Image)bmpSource, 0, 0, (int)(bmpSource.Width * ratio), (int)(bmpSource.Height * ratio));
                            g.Dispose();
                            bmpTarget.Save(OutStream, ImageFormat.Jpeg);
                        }
                        break;
                    case ".gif":
                        g.DrawImage((System.Drawing.Image)bmpSource, 0, 0, (int)(bmpSource.Width * ratio), (int)(bmpSource.Height * ratio));
                        g.Dispose();
                        bmpTarget.Save(OutStream, ImageFormat.Gif);
                        break;
                    case ".png":
                        g.DrawImage((System.Drawing.Image)bmpSource, 0, 0, (int)(bmpSource.Width * ratio), (int)(bmpSource.Height * ratio));
                        g.Dispose();
                        bmpTarget.Save(OutStream, ImageFormat.Png);
                        break;
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogDataRecord.LDR log = new LogDataRecord.LDR(@MensUnoShop.Models.Config.logpath);
                log.RecordException(ex.GetBaseException().ToString(), "SaveUploadImage");
            }
            finally
            {
                OutStream.Close();
                OutStream.Dispose();
                bmpTarget.Dispose();
                bmpSource.Dispose();
            }
        }



        /// <summary>
        /// 儲存上傳圖檔
        /// </summary>
        /// <param name="ADimage">圖片檔案</param>
        /// <param name="AppSettingsDir">上傳路徑</param>
        /// <param name="NewFileNameTopHeader">新檔案名稱標題</param>
        /// <param name="ifwantTransImage">是否要縮圖</param>
        /// <param name="TargetWidth">縮圖寬度(建議:300)</param>
        /// <returns></returns>
        public SaveUploadMessage SaveUploadImage(HttpPostedFileBase ADimage, string AppSettingsDir, string NewFileNameTopHeader, bool ifwantTransImage, int TargetWidth)
        {
            return _mSaveUploadImage(ADimage, AppSettingsDir, NewFileNameTopHeader, ifwantTransImage, TargetWidth);
        }


        /// <summary>
        /// 上傳圖片回傳訊息
        /// </summary>
        public class SaveUploadMessage
        {
            public SaveUploadMessage()
            {
                saveStatus = false;
                NewFileName = string.Empty;
                SaveErrorMessage = string.Empty;
            }
            public bool saveStatus
            {
                get;
                set;
            }
            public string NewFileName
            {
                get;
                set;
            }

            public string SaveErrorMessage
            {
                get;    
                set;
            }
        }

    }
}